<?php
namespace app\jobmanagement\service;

use app\constdir\ApiConst;
use think\Exception;
use app\model\Product as mProduct;
use app\model\ProductWork as mProductWork;
use app\model\TaskTask as mTaskTask;

/**
 * Class Product
 * @package app\jobmanagement\service
 */
class Product
{
    private $mProduct;
    private $mProductWork;
    private $mTaskTask;
    private $cProdUnit;
    private $dd_user_id;
    private $dept_id;
    public function __construct(){
        $this->mProduct = new mProduct();
        $this->mProductWork = new mProductWork();
        $this->mTaskTask = new mTaskTask();
        $unit = [];
        foreach (config('dic.prod_unit') as $key => $value){
            $unit[$key]['id'] =  $key;
            $unit[$key]['name'] = $value;
        }
        $this->cProdUnit = $unit;
        $this->dd_user_id = session('dd_user_id');
        $this->dept_id = session('dept_id');
    }


    /**
     * @introduction:产品的添加修改以及工种的变更修改
     * @param $param
     * @return bool|string
     * @throws \think\exception\PDOException
     * @author:cxh
     * @date: 2020/5/20 11:00
     */
    public function productSave($param){
        //启动事务
        $this->mProduct->startTrans();
        try {
            $date_time = date("Y-m-d H:i:s",time());
            $user = $this->dd_user_id;
            switch ($param['type']){
                case 1:
                    //当新增时如果有产品ID表示错误
                    if(!empty($param['id'])){
                        return ['code'=> ApiConst::PRODUCT_ADD_PROD_ID_ERROR_CODE, 'msg'=>ApiConst::PRODUCT_ADD_PROD_ID_ERROR_MSG];
                    }
                    $data = [
                        'name' => $param['name'],
                        'amount' => $param['amount'],
                        'unit' => $param['unit'],
                        'dept_id' => $this->dept_id,
                        'create_time' => $date_time,
                        'create_user' => $user,
                        'update_time' => $date_time,
                        'update_user' => $user,
                    ];
                    $prod_id = $this->mProduct
                        ->insertGetId($data);
                    if(empty($prod_id)){
                        return ['code'=> ApiConst::PRODUCT_ADD_RETURN_ID_ERROR_CODE, 'msg'=>ApiConst::PRODUCT_ADD_RETURN_ID_ERROR_MSG];
                    }
                    //获取新增的产品ID从而进行工种的添加
                    $prod_work = $this->productWorkSave($param['work'],$prod_id);
                    break;

                case 2:
                    //当编辑时如果没有产品ID表示错误
                    if(empty($param['id'])){
                        return ['code'=> ApiConst::PRODUCT_EDIT_PROD_ID_ERROR_CODE, 'msg'=>ApiConst::PRODUCT_EDIT_PROD_ID_ERROR_MSG];
                    }
                    $data_up = [
                        'name' => $param['name'],
                        'amount' => $param['amount'],
                        'unit' => $param['unit'],
                        'update_time' => $date_time,
                        'update_user' => $user,
                    ];
                    $prod_id = $this->mProduct
                        ->where('id',$param['id'])
                        ->update($data_up);

                    //根据修改的ID进行工种的操作
                    $prod_work = $this->productWorkSave($param['work'],$param['id']);
                    break;
            }
            //提交事务
            $this->mProduct->commit();
        }catch (\Exception $e){
            //事务回滚
            $this->mProduct->rollback();
            return ['code'=> ApiConst::FAILED_CODE, 'msg'=> $e->getMessage()];
        }

        return true;

    }


    /**
     * @introduction:通过传入的JSON数据进行产品工种的处理
     * @param $param
     * @param $prod_id
     * @return bool|string|null
     * @author:cxh
     * @date: 2020/5/20 10:25
     */
    public function productWorkSave($param,$prod_id){

        $workList = json_decode($param,true);

        if(empty($workList) or empty($prod_id)){
            return ['code'=> ApiConst::PRODUCT_WORK_ADD_ERROR_CODE, 'msg'=>ApiConst::PRODUCT_WORK_ADD_ERROR_MSG];
        }
        $idAll = null;

        foreach ($workList as $value){
            switch ($value['type']){
                case 1 : //新增
                    if(!empty($value['id'])){
                        return ['code'=> ApiConst::PRODUCT_WORK_ADD_ID_ERROR_CODE, 'msg'=>ApiConst::PRODUCT_WORK_ADD_ID_ERROR_MSG];
                    }
                    $addWork = $this->mProductWork
                        ->insertGetId(['name'=>$value['name'],'prod_id'=>$prod_id]);
                    $idAll .= $addWork.',';
                    break;
                case 2: //编辑
                    if(empty($value['id'])){
                        return ['code'=> ApiConst::PRODUCT_WORK_EDIT_ID_ERROR_CODE, 'msg'=>ApiConst::PRODUCT_WORK_EDIT_ID_ERROR_MSG];
                    }
                    $updateWork = $this->mProductWork
                        ->where(['id'=>$value['id'],'prod_id'=>$prod_id])
                        ->update(['name' => $value['name'],'prod_id'=>$prod_id]);
                    $idAll .= $value['id'].',';
                    break;
                case 3: //删除
                    if(empty($value['id'])){
                        return ['code'=> ApiConst::PRODUCT_WORK_DELETE_ID_ERROR_CODE, 'msg'=>ApiConst::PRODUCT_WORK_DELETE_ID_ERROR_MSG];
                    }
                    $deleteWork = $this->mProductWork
                        ->where(['id'=>$value['id'],'prod_id'=>$prod_id])
                        ->delete();
                    break;
            }

        }

        return !empty($idAll) ? rtrim($idAll,',') : null;

    }


    /**
     * @introduction:产品新增或者编辑所需内容视图页输出
     * @param $param
     * @return array|bool|false|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author:cxh
     * @date: 2020/5/20 14:48
     */
    public function productEdit($param){
        //根据type来判定是编辑还是新增

        $data = [];
        $work_list = [];
        if($param['type'] == 2){
            $data = $this->mProduct
                ->field('id,name,amount,unit')
                ->where('id',$param['id'])
                //->where('create_user',$this->dd_user_id)
                ->find();
            if(empty($data)){
                return ['code'=> ApiConst::PRODUCT_INFO_ERROR_CODE, 'msg'=>ApiConst::PRODUCT_INFO_ERROR_MSG];
            }

            $data['unit_cn'] = !empty($this->cProdUnit[$data['unit']]['name']) ? $this->cProdUnit[$data['unit']]['name'] : null;
            $work_list = $this->mProductWork
                ->where('prod_id',$param['id'])
                ->select();
        }

        //单位列表
        if(!empty($work_list)){
            $data['work_list'] = $work_list;
        }
        $data['unit_list'] = $this->cProdUnit;

        return $data;
    }


    /**
     * @introduction:根据分页获取对应用户的产品列表
     * @param $param
     * @return bool|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author:cxh
     * @date: 2020/5/20 16:12
     */
    public function productList($param){

        $page_num = PAGE_SIZE;
        $page = ($param['page'] - 1) * $page_num;
        $add_where = ['dept_id' => $this->dept_id];
        $prod_list = $this->mProduct
            //->where('create_user',$this->dd_user_id)
            ->where($add_where)
            ->limit($page,$page_num)
            ->order('id desc')
            ->select();
        foreach ($prod_list as $key => $value){
           $prod_list[$key]['unit_cn'] =  !empty($this->cProdUnit[$value['unit']]['name']) ? $this->cProdUnit[$value['unit']]['name'] : null;
        }
        return $prod_list;
    }


    /**
     * @introduction:根据产品ID查询出详细信息以及工种信息
     * @param $param
     * @return array|bool|false|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author:cxh
     * @date: 2020/5/20 16:27
     */
    public function productInfo($param){

        $data = $this->mProduct
                ->field('id,name,amount,unit')
                ->where('id',$param['id'])
                //->where('create_user',$this->dd_user_id)
                ->find();

        if(empty($data)){
            return ['code'=> ApiConst::PRODUCT_INFO_ERROR_CODE, 'msg'=>ApiConst::PRODUCT_INFO_ERROR_MSG];
        }
        $data['unit_cn'] = !empty($this->cProdUnit[$data['unit']]['name']) ? $this->cProdUnit[$data['unit']]['name'] : null;
        $work_list = $this->mProductWork
                ->where('prod_id',$param['id'])
                ->select();

        if(!empty($work_list)){
            $data['work_list'] = $work_list;
        }
        return $data;

    }


    /**
     * @introduction:根据参数产品ID去删除对应的产品
     * @param $param
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author:cxh
     * @date: 2020/5/23 16:37
     */
    public function productDelete($param){
        //查询该产品下面是否存在任务单
        $task = $this->mTaskTask
            ->where('prod_id',$param['id'])
            ->find();
        if(!empty($task)){
            return ['code'=> ApiConst::PRODUCT_DELETE_TASK_ERROR_CODE, 'msg'=>ApiConst::PRODUCT_DELETE_TASK_ERROR_MSG];
        }
        //启动事务
        $this->mProduct->startTrans();
        try {
            //删除产品
            $data = $this->mProduct
                ->where('id',$param['id'])
                //->where('create_user',$this->dd_user_id)
                ->delete();
            //删除产品下面工种
            $data = $this->mProductWork
                ->where('prod_id',$param['id'])
                //->where('create_user',$this->dd_user_id)
                ->delete();
            //提交事务
            $this->mProduct->commit();
            return true;
        }catch (Exception $e){
            //回滚事务
            $this->mProduct->rollback();
            return ['code'=> ApiConst::PRODUCT_DELETE_PRODUCT_ERROR_CODE, 'msg'=>ApiConst::PRODUCT_DELETE_PRODUCT_MSG];
        }



    }



}




























